package com.banshuibao.bsb_android.activity;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.banshuibao.bsb_android.Constants;
import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.http.HttpResponse;
import com.banshuibao.bsb_android.http.HttpUtil;
import com.banshuibao.bsb_android.model.RecorderModel;
import com.banshuibao.bsb_android.model.RecorderSendModel;
import com.banshuibao.bsb_android.model.RequestOkModel;
import com.banshuibao.bsb_android.util.ClearDirUtil;
import com.banshuibao.bsb_android.util.DownTimerUtil;
import com.banshuibao.bsb_android.util.MediaPlayerUtil;
import com.banshuibao.bsb_android.util.MyEditText;
import com.banshuibao.bsb_android.util.RecorderUtil;
import com.banshuibao.bsb_android.util.TimeUtil;
import com.banshuibao.bsb_android.util.XToast;
import com.zx.uploadlibrary.listener.impl.UIProgressListener;

import java.io.File;

public class AdditionalRecorderActivity extends PermissionBaseActivity implements View.OnClickListener, MediaPlayerUtil.MediaPlayerPlayingListener {

    private String uuid,title_tv,recorder_content,recorder_price;
    private Dialog dialog;
    private TextView download_status;
    private ProgressBar progressBar;
    private Chronometer chronometer;
    private long recordingTime = 0;// 记录下来的总时间
    private long timer = 0;// 记录下来的总时间
    private RecorderUtil recorderUtil;
    private ImageView bt_start;
    private int flag = 0;
    private MediaPlayerUtil mediaPlayerUtil;
    private TextView commit, bt_restart;
    private TextView downTimer;
    private File file = new File(Constants.LocalFile.DIR);
    private SharedPreferences sp;
    private DownTimerUtil downTimerUtil;
    private String time_tv;
    private TextView title;
    private MyEditText editText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_additional_recorder);
        sp = getSharedPreferences("record_add", MODE_PRIVATE);
        recorderUtil = new RecorderUtil(this);
        uuid = getIntent().getStringExtra("uuid");
        title_tv = getIntent().getStringExtra("title");
        recorder_price = getIntent().getStringExtra("price");
        initView();
    }

    public void initView() {
        setTitleText("修改录音");
        commit = findViewById(R.id.menu);
        commit.setVisibility(View.VISIBLE);
        commit.setText("提交");
        back_iv = findViewById(R.id.back_iv);
        bt_start = findViewById(R.id.bt_start);
        bt_restart = findViewById(R.id.bt_restart);
        chronometer = findViewById(R.id.timer);
        downTimer = findViewById(R.id.downTimer);
        title = findViewById(R.id.title);
        editText = findViewById(R.id.content);
        bt_start.setOnClickListener(this);
        bt_restart.setOnClickListener(this);
        commit.setOnClickListener(this);
        back_iv.setOnClickListener(this);
        mediaPlayerUtil = new MediaPlayerUtil(this);
        mediaPlayerUtil.setOnMediaPlayerPlayingListener(this);
        downTimerUtil = new DownTimerUtil();
        downTimerUtil.setOnTimerChangeListener(listener);
        setData();
    }
    public void setData(){
        title.setText(title_tv);
    }

    /**
     * 开始录音
     */
    public void startRecorder() {
        flag = 1;
        recorderUtil.startRecord();
        chronometer.setBase(SystemClock.elapsedRealtime());//计时器清零
        int hour = (int) ((SystemClock.elapsedRealtime() - chronometer.getBase()) / 1000 / 60);
        chronometer.setFormat("0" + String.valueOf(hour) + ":%s");
        chronometer.start();
    }

    /**
     * 停止录音
     */
    public void stopRecord() {
        flag = 2;
        bt_restart.setVisibility(View.VISIBLE);
        recorderUtil.stopRecord();
        if (chronometer != null) {
            chronometer.stop();
            recordingTime = SystemClock.elapsedRealtime() - chronometer.getBase();// 保存这次记录了的时间
            time_tv = TimeUtil.formatDuring(recordingTime);
        }
    }

    /**
     * 播放录音
     */
    public void playRecord() {
        flag = 3;
        chronometer.setVisibility(View.GONE);
        downTimer.setVisibility(View.VISIBLE);
        mediaPlayerUtil.getLocalMedia(Constants.LocalFile.DIR);
        downTimer.setText(time_tv);
        downTimerUtil.startTime(recordingTime, 1000);
    }

    /**
     * 暂停播放
     */
    public void playPause() {
        flag = 4;
        mediaPlayerUtil.setPause();
        downTimerUtil.endTimer();
        downTimer.setText(TimeUtil.formatDuring(timer));
    }

    /**
     * 继续播放
     */
    public void goPlay() {
        flag = 3;
        mediaPlayerUtil.setPlay();
        chronometer.setVisibility(View.GONE);
        downTimer.setVisibility(View.VISIBLE);
        downTimer.setText(TimeUtil.formatDuring(timer));
        downTimerUtil.startTime(timer, 1000);
    }

    /**
     * 重新录音
     */
    public void resetRecord() {
        flag = 0;
        if (chronometer != null) {
            recordingTime = 0;//重置时间
            chronometer.setBase(SystemClock.elapsedRealtime());
            chronometer.stop();
        }
        downTimer.setVisibility(View.GONE);
        chronometer.setVisibility(View.VISIBLE);
        setBtStatus(flag);
        ClearDirUtil.clearAll(file);//清空文件
        sp.edit().clear().commit();//清空缓存
        mediaPlayerUtil.clearMediaPlayer();
    }

    @Override
    public void successGrantPermission(int requestCode) {
        if(!RecorderUtil.isHasPermission()){
            recorderUtil.AskForPermission();
            XToast.showToast(AdditionalRecorderActivity.this,"请手动打开录音权限");
            return;
        }
        if (flag == 0) {//开始录音
            startRecorder();
        } else if (flag == 1) {//停止录音
            stopRecord();
        } else if (flag == 2) {//播放录音
            playRecord();
        } else if (flag == 3) {//暂停播放
            playPause();
        } else if (flag == 4) {
            goPlay();
        }
        setBtStatus(flag);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_start:
                requestUserPermission(view, Manifest.permission.RECORD_AUDIO, 200);
                break;
            case R.id.bt_restart:
                resetRecord();
                break;
            case R.id.menu:
                if (flag == 1) {
                    stopRecord();
                    setBtStatus(flag);
                }
                if (mediaPlayerUtil != null) {
                    mediaPlayerUtil.clearMediaPlayer();
                }
                if (downTimerUtil != null) {
                    downTimerUtil.endTimer();
                }
                 recorder_content = editText.getText().toString().trim();
                if(TextUtils.isEmpty(recorder_content)){
                    XToast.showToast(AdditionalRecorderActivity.this,"请输入录音文本");
                    return;
                }
                showDialog();
                break;
            case R.id.back_iv:
                saveTime();
                finish();
                break;
        }

    }

    public void load(UIProgressListener listener) {
        HttpUtil.doUpload(Constants.Url.SEND_RECORDER, Constants.LocalFile.DIR, listener, new HttpResponse(this, RecorderSendModel.class) {
            @Override
            public void onResult(Object obj) {
                RecorderSendModel model = (RecorderSendModel) obj;
                toastUpload_status("上传成功");
                String name = model.getData();
                sendContent(name);
            }

            @Override
            public void onError(String code, String msg) {
                super.onError(code, msg);
                if (dialog != null) {
                    dialog.dismiss();
                }
                XToast.showToast(AdditionalRecorderActivity.this, msg);
            }

            @Override
            public void onFailure(String msg) {
                super.onFailure(msg);
                if (dialog != null) {
                    dialog.dismiss();
                }
                XToast.showToast(AdditionalRecorderActivity.this, msg);
            }

            @Override
            public void responseEnd() {
                super.responseEnd();
                cancelProgressDialog();
            }
        });
    }

    /**
     * type  0 发布 1 补录
     * content 问题内容
     * uuid	问题的uuid 补录时必传
     * voiceText	语音文本
     * voiceTime	语音时长
     * askPrice	追问价格
     * areaId	   地区id 全国（00）
     * trade		行业
     * tax		税种
     * topic	   专题
     * voiceName	语音名字
     *
     * @param name
     */
    public void sendContent(String name) {
        final RecorderModel recorderModel = new RecorderModel();
        recorderModel.setType("1");
        recorderModel.setVoiceName(name);
        recorderModel.setVoiceText(recorder_content);
        recorderModel.setVoiceTime(recordingTime);
        recorderModel.setUuid(uuid);
        recorderModel.setAskPrice(Double.valueOf(recorder_price));
        HttpUtil.doPost(Constants.Url.SEND_EXPERT_RELEASE, recorderModel, new HttpResponse(this, RequestOkModel.class) {
            @Override
            public void onResult(Object obj) {
                if (dialog != null) {
                    dialog.dismiss();
                }
                if (chronometer != null) {
                    recordingTime = 0;//重置时间
                    chronometer.setBase(SystemClock.elapsedRealtime());
                }
                ClearDirUtil.clearAll(file);
                RequestOkModel requestOkModel = (RequestOkModel) obj;
                XToast.showToast(AdditionalRecorderActivity.this, "上传成功");
                setResult(RESULT_OK);
                finish();
            }

            @Override
            public void onError(String code, String msg) {
                super.onError(code, msg);
                if (dialog != null) {
                    dialog.dismiss();
                }
                XToast.showToast(AdditionalRecorderActivity.this, msg);
            }

            @Override
            public void onFailure(String msg) {
                super.onFailure(msg);
                if (dialog != null) {
                    dialog.dismiss();
                }
                XToast.showToast(AdditionalRecorderActivity.this, msg);
            }

        });
    }

    private void showUploadDialog() {
        if (!file.exists()) {
            XToast.showToast(this, "录音文件不存在,请录音...");
            return;
        }
        if (dialog == null) {
            View view = LayoutInflater.from(this).inflate(R.layout.dialog_download_progress, null);
            TextView title = (TextView) view.findViewById(R.id.title);
            title.setText("上传中请稍后");
            download_status = (TextView) view.findViewById(R.id.download_status);
            download_status.setText("正在上传");
            progressBar = (ProgressBar) view.findViewById(R.id.progress_bar);
            dialog = new AlertDialog.Builder(this).setView(view).setCancelable(false).create();
        }
        if (!this.isDestroyed())
            dialog.show();
        uploadFile();
    }

    private void setUpload_status(String msg) {
        if (download_status != null) {
            download_status.setText(msg);
        }
    }

    private void toastUpload_status(String msg) {
        setUpload_status(msg);
    }

    private void uploadFile() {
        UIProgressListener listener = new UIProgressListener() {
            @Override
            public void onUIProgress(long l, long l1, boolean b) {
                if (l1 == 0)
                    return;
                int progress = (int) ((100 * l) / l1);
                progressBar.setProgress(progress);
                if (dialog != null && dialog.isShowing())
                    setUpload_status("上传进度: " + progress + "%");
            }

            @Override
            public void onUIStart(long currentBytes, long contentLength, boolean done) {
                super.onUIStart(currentBytes, contentLength, done);
            }

            @Override
            public void onUIFinish(long currentBytes, long contentLength, boolean done) {
                super.onUIFinish(currentBytes, contentLength, done);

            }
        };
        load(listener);
    }

    /**
     * 根据flag显示不同状态
     */
    public void setBtStatus(int flag) {
        switch (flag) {
            case 0://开始
                bt_start.setImageResource(R.drawable.start_bt);
                break;
            case 1://停止
                bt_start.setImageResource(R.drawable.stop_bt);
                break;
            case 2://播放
                bt_start.setImageResource(R.drawable.play_bt);
                break;
            case 3://暂停
                bt_start.setImageResource(R.drawable.pause_bt);
                break;
            case 4://暂停
                bt_start.setImageResource(R.drawable.play_bt);
                break;
        }
    }

    @Override
    public void OnError(MediaPlayer mediaPlayer) {

    }

    @Override
    public void OnPrepared(MediaPlayer mediaPlayer) {

    }

    @Override
    public void OnCompletion(MediaPlayer mediaPlayer) {
        flag = 2;
        bt_start.setImageResource(R.drawable.play_bt);
        downTimer.setText(time_tv);
        downTimer.setVisibility(View.VISIBLE);
        chronometer.setVisibility(View.GONE);
    }

    /**
     * 判断本地是否存有此文件
     */
    public void readLocalFile() {
        if (file.isFile() && file.exists()) {
            flag = 2;
            bt_start.setImageResource(R.drawable.play_bt);
            bt_restart.setVisibility(View.VISIBLE);
        }
        readTime();
    }

    /**
     * 将录音时长进行保存
     */
    public void saveTime() {
        if (recordingTime == 0) return;
        SharedPreferences.Editor editor = sp.edit();
        editor.putLong("time", recordingTime).commit();
    }

    /**
     * 查看是否有录音文件时长
     */
    public void readTime() {
        long time = sp.getLong("time", 0);
        if (time > 0) {
            recordingTime = time;
            time_tv = TimeUtil.formatDuring(recordingTime);
            chronometer.setVisibility(View.GONE);
            downTimer.setVisibility(View.VISIBLE);
            downTimer.setText(time_tv);
        } else {
            downTimer.setVisibility(View.GONE);
            chronometer.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 倒计时
     */
    DownTimerUtil.OnTimerChangeListener listener = new DownTimerUtil.OnTimerChangeListener() {
        @Override
        public void OnTick(long l) {
            long time = l / 1000;
            timer = l;
            if (time <= 59) {
                downTimer.setText(String.format("00:00:%02d", time));
            } else {
                downTimer.setText(String.format("%02d:%02d:%02d",time/3600 ,time / 60, time % 60));
            }
        }

        @Override
        public void OnFinish() {
            downTimerUtil.endTimer();
            downTimer.setText(time_tv);
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            saveTime();
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mediaPlayerUtil.clearMediaPlayer();
    }

    /**
     * 弹窗
     */
    public void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this).setCancelable(false);  //先得到构造器
        builder.setTitle("提示"); //设置标题
        builder.setMessage("确定发布此录音文件"); //设置内容
        builder.setPositiveButton("发布", new DialogInterface.OnClickListener() { //设置确定按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                showProgressDialog();
                showUploadDialog();
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { //设置取消按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        //参数都设置完成了，创建并显示出来
        builder.create().show();
    }
}
